<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>User</title>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link href="./EldercareMasterPage/_finalstyle.css" rel="stylesheet" />
	<link href="./css/bootstrap.min.css" rel="stylesheet" media="screen">
    <link href="./css/bootstrap-datetimepicker.min.css" rel="stylesheet" media="screen">
	<link rel="stylesheet" type="text/css" href="./jquery/easyui.css">	
    <link rel="stylesheet" type="text/css" href="./jquery/icon.css">
    <style>
		.easyui-dialog{
		    height:425px!important;
		}
		.panel-window{
		    height:390px!important;
		}
	</style>
</head>
<?php
	define('CONFIG_FILE',true);
	include './config.php';
	define('DB_FILE',true);

	session_start();
	if (empty($_SESSION["username"])||empty($_SESSION["userType"])) {
		Header("Location: ./Index.php");
		exit();
	}else{
		$userType = $_SESSION["userType"];
	}
	if($userType=="Therapy Assistant"){
		$url="./Index.php";
		include_once './Tool/Common/Redirect.php';
		exit();
	}
	// set timeout period in seconds
	$inactive = 7200;
	// check to see if $_SESSION['timeout'] is set
	if(isset($_SESSION["timeout"])){
		$session_life = time() - $_SESSION["timeout"];
		if($session_life > $inactive){
			session_destroy(); 
			Header("Location: Timeout.php"); 
		}
	}
	$_SESSION["timeout"] = time();
?>
<body>
	<div class="banner">
	</div>
	<div id="main">
		<div class="left-wrapper">
			<div class="logo">
				<img src="images/eldercare.gif" alt="logo" width="240px" />
			</div>
			<div class="menu-wrapper">
				<div id="cssmenu">
					<?php
						if ($userType == "Therapy Assistant") {
							include_once('./Sidebar/_SidebarTA.php');
						} else if ($userType == "Centre Manager") {
							include_once('./Sidebar/_SidebarCM.php');
						} else {
							include_once('./Sidebar/_SidebarSA.php');
						}
					?>
				</div>
			</div>
		</div>           
		<div id="content">
		   <div class="content2">
				<b style="float:right; margin: 0px 0 0 0">  
					<?php
						if(!empty($_SESSION["centreName"])){   
							$Username = $_SESSION["username"];
							$centreName = $_SESSION["centreName"];
							echo "Welcome, " . $Username . " ! " . $centreName. " Branch";
						}
						else{
							$Username = $_SESSION["username"];
							echo "Welcome, " . $Username;
						}
					?>

					<input type="submit" class="btn btn-danger" value="Logout" onclick="parent.location = 'logout.php'">
				</b>
				</p>
				<br>
			<div style="float:center">
				<br>
				<h3>Users</h3>
				<br>			
				<table id="dg" title="User" class="easyui-datagrid" style="width:auto;height:430px; "
						url="CRUDUser/get_user.php"
						toolbar="#toolbar" pagination="true"
						rownumbers="true" fitColumns="true" singleSelect="true">
					<thead>
						<tr>
							<th field="Username" width="50" sortable="true">Username</th>
							<th field="StaffName" width="50" sortable="true">Staff Name</th>
							<th field="UserType" width="50" sortable="true">User Type</th>
							<th field="CentreName" width="50" sortable="true">Centre Name</th>
							<th field="ContactNumber" width="50">Contact Number</th>
							<th field="Email" width="50">Email</th>
							<tbody style="display:none">
							<th field="CentreId" width="50">Centre ID</th>
						</tr>
					</thead>
				</table>
				<div id="toolbar">
					<a href="#" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="newUser()">New User</a>
					<a href="#" class="easyui-linkbutton" iconCls="icon-edit" plain="true" onclick="editUser()">Edit User</a>
					<a href="#" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onclick="removeUser()">Remove User</a>
					<input id="searchid" name="searchid" type="text" style="border-radius:25px">  
					<a href="#" class="easyui-linkbutton" iconCls="icon-search" onClick="getUser()">Search</a>
					<a href="#" class="easyui-linkbutton" onClick="findAll()">All</a>
				</div>

				<!-- Update Dialog -->
				<div>
					<div id="insertdlg" class="easyui-dialog" style="width:400px;height:330px;padding:10px 20px"
							closed="true" buttons="#insertdlg-buttons">
						<div class="ftitle">User Information</div>
						<form id="insertform" method="post" novalidate>
							<div class="fitem">
								<label>Username: </label>
								<input id="InsertUsername"name="InsertUsername" class="easyui-validatebox" required="true"style="width:155" height='auto'>
							</div>
							<div class="fitem">
								<label>Password: </label>
								<input id="InsertPassword"name="InsertPassword" type="Password" class="easyui-validatebox" required="true"style="width:155" height='auto'>
							</div>
							<div class="fitem">
								<label>User Type: </label>
								<select id="InsertUserType" name="InsertUserType"required ="true" class="easyui-combobox"style="width:155" height='auto'>
									<?php
										if($userType=="Centre Manager"){
											echo "<option value='Therapy Assistant' selected>Therapy Assistant</option>";
										}
										else{
											echo "<option value='Therapy Assistant' selected>Therapy Assistant</option>
										    <option value='Centre Manager'>Centre Manager</option>
						                	<option value='Super User'>System Admin</option>";
										}
									?>
								</select>
							</div>
							<div class="fitem">
								<label>Staff Name: </label>
								<input id="InsertStaffName" name="InsertStaffName" class="easyui-validatebox" required="true"style="width:155" height='auto'>
							</div>
							<div class="fitem">
								<label>Contact Number: </label>
								<input id="InsertContactNumber" name="InsertContactNumber" style="width:155" height='auto'>
							</div>
							<div class="fitem">
								<label>Email: </label>
								<input id= "InsertEmail" name="InsertEmail" required = "true" class="easyui-validatebox" data-options="validType:'email'"style="width:155" height='auto'>
							</div>
							<div class="fitem">
								<label>Centre: </label>
								<select id="InsertCentreId" name="InsertCentreId" required = "true" class="easyui-combobox"style="width:155" height='auto'>
								<?php
									require_once './Tool/DB/SqlDBManager.class.php';
									$sqlDBManager = new SqlDBManager();
									if($_SESSION["userType"]=="System Admin"){
										$sql="SELECT CentreId, CentreName FROM centre";  
										$res=$sqlDBManager->queryRows($sql); 
									}
									else{
										$sql="SELECT CentreId, CentreName FROM centre where CentreName=?";
										$parameters=array($_SESSION["centreName"]);
										$res=$sqlDBManager->queryRows($sql,$parameters);
									}		
									if(!empty($res)){
										for($i=0;$i<count($res);$i++){
											echo "<option value=\"".$res[$i]['CentreId']."\">".$res[$i]['CentreName']."</option>";			
										}
									}
									//close connection
										$sqlDBManager->close_connect();
								?>
								</select>
							</div>
						</form>
					</div>
					<div id="insertdlg-buttons">
						<a href="#" class="easyui-linkbutton" iconCls="icon-ok" onclick="saveUser()">Save</a>
						<a href="#" class="easyui-linkbutton" iconCls="icon-cancel" onclick="insertCancel();">Cancel</a>
					</div>
				</div>		
					
				<!-- Update Dialog -->
				<div>
					<div id="updatedlg" class="easyui-dialog" style="width:400px;height:330px;padding:10px 20px"
							closed="true" buttons="#updatedlg-buttons">
						<div class="ftitle">User Information</div>
						<form id="updateform" method="post" novalidate>
							<div class="fitem">
								<label>Username: </label>
								<input id="UpdateUsername" name="Username" class="easyui-validatebox" required="true" readonly = "true"style="width:155" height='auto'>
							</div>
							<div class="fitem">
								<label>User Type: </label>
								<select id="UpdateUserType" name="UserType"required ="true" class="easyui-combobox"style="width:155" height='auto'>
								<?php
									if($userType=="Centre Manager"){
										echo "<option value='Centre Manager'>Centre Manager</option>";
									}
									else{
										echo "<option value='Therapy Assistant'>Therapy Assistant</option>
									 		<option value='Centre Manager'>Centre Manager</option>
											<option value='Super User'>System Admin</option>";
									}
								?>
								</select>
							</div>
							<div class="fitem">
								<label>Staff Name: </label>
								<input id="UpdateStaffName" name="StaffName" class="easyui-validatebox" required="true"style="width:155" height='auto'>
							</div>
							<div class="fitem">
								<label>Contact Number: </label>
								<input id="UpdateContactNumber" name="ContactNumber"style="width:155" height='auto'>
							</div>
							<div class="fitem">
								<label>Email: </label>
								<input id="UpdateEmail" name="Email" id="UpdateEmail" required = "true" class="easyui-validatebox" data-options="validType:'email'"style="width:155" height='auto'>
							</div>
							<div class="fitem">
								<label>Centre: </label>
								<select id="UpdateCentreId" name="CentreId" required = "true" class="easyui-combobox"style="width:155" height='auto'>
								<?php
									require_once './Tool/DB/SqlDBManager.class.php';
									$sqlDBManager = new SqlDBManager();
									if($_SESSION["userType"]=="System Admin"){
										$sql="SELECT CentreId, CentreName FROM centre";  
										$res=$sqlDBManager->queryRows($sql); 
									}
									else{
										$sql="SELECT CentreId, CentreName FROM centre where CentreName=?";
										$parameters=array($_SESSION["centreName"]);
										$res=$sqlDBManager->queryRows($sql,$parameters);
									}		
									if(!empty($res)){
										for($i=0;$i<count($res);$i++){
											echo "<option value=\"".$res[$i]['CentreId']."\">".$res[$i]['CentreName']."</option>";			
										}
									}
									//close connection
										$sqlDBManager->close_connect();
								?>
								</select>
							</div>
						</form>
					</div>
					<div id="updatedlg-buttons">
						<a href="#" class="easyui-linkbutton" iconCls="icon-ok" onclick="updateUser()">Save</a>
						<a href="#" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#updatedlg').dialog('close')">Cancel</a>
					</div>
				</div>
			</div>
			<p>
        </div>
	    <div class="clear"></div>
    	</div>
	</div>
	<div id="footer">&copy; 2013 MP22 IIT-IT Temasek Polytechnic</div>
</body> 
<script type="text/javascript" src="./jquery/jquery-1.6.1.min.js"></script>	
<script type="text/javascript" src="./jquery/jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="./jquery/jquery.easyui.min.js"></script>
<script type="text/javascript">
	var url;
	function newUser(){
		$('#insertdlg').dialog('open').dialog('setTitle','New User');
	}

	function saveUser(){
		$('#insertform').form('submit',{
			onSubmit: function(){
				$(this).form('validate');	
				//validate input		
				var flagUserName=0;
				var flagUserNameExist=0;
				var flagPasswordLength=0;
				var flagPasswordMatch=0;
				var flagPasswordContain=0;
				var flagPasswordLowercase=0;
				var flagPasswordUppercase=0;
				var flagPasswordWhitespace=0;
				var flagStaffName=0;
				var flagContactNo=0;
				var flagUserType=0;
				var flagCentreId=0;
				var flagEmailFormat=0;
				var flagEmailExist=0;

				$.ajax({
					async : false,
					type : "POST",
					url : "./CRUDUser/validateInsert.php", //the page/method you wanna validate
					data : {
						InsertUsername: $("#InsertUsername").val(),
						InsertPassword: $("#InsertPassword").val(),
						InsertStaffName:$("#InsertStaffName").val(),
						InsertContactNo:$("#InsertContactNumber").val(),
						InsertUserType: $('[name="InsertUserType"]').val(),
						InsertCentreId: $('[name="InsertCentreId"]').val(),
						InsertEmail: $("#InsertEmail").val()
					},
					success : function(data) {
						var data = JSON.parse(data);
						flagUserName=data.flagUserName;
						flagUserNameExist=data.flagUserNameExist;
						flagPasswordLength=data.flagPasswordLength;
						flagPasswordMatch=data.flagPasswordMatch;
						flagPasswordContain=data.flagPasswordContain;
						flagPasswordLowercase=data.flagPasswordLowercase;
						flagPasswordUppercase=data.flagPasswordUppercase;
						flagPasswordNumber=data.flagPasswordNumber;
						flagPasswordWhitespace=data.flagPasswordWhitespace;
						flagStaffName=data.flagStaffName;
						flagContactNo=data.flagContactNo;
						flagUserType=data.flagUserType;
						flagCentreId=data.flagCentreId;
						flagEmailFormat=data.flagEmailFormat;
						flagEmailExist=data.flagEmailExist;
					}
				});
				if(flagUserName==0){
					$.messager.show({
						title: 'Error',
						msg: 'Invalid Username. Username cannot contain any special characters.',
						showType:'fade',
						style:{
		                    right:'',
                    		bottom:''
		                }
					});
					die; 
				}else if(flagUserNameExist==0){
					$.messager.show({
						title: 'Error',
						msg: 'This Username has already been used! Please enter another Username.',
						showType:'fade',
						style:{
		                    right:'',
                    		bottom:''
		                }
					});
					die; 
				}else if(flagPasswordLength==0){
					$.messager.show({
						title: 'Error',
						msg: 'Your password must be at least 8 characters long.Your password must be at least 8 characters long and contain upper and lowercase letters, a number without white space.',
						showType:'fade',
						style:{
		                    right:'',
                    		bottom:''
		                }
					});
					die; 
				}else if(flagPasswordMatch==0){
					$.messager.show({
						title: 'Error',
						msg: 'Your password must not match your username.Your password must be at least 8 characters long and contain upper and lowercase letters, a number without white space.',
						showType:'fade',
						style:{
		                    right:'',
                    		bottom:''
		                }
					});
					die; 
				}else if(flagPasswordContain==0){
					$.messager.show({
						title: 'Error',
						msg: 'Your password must not contain your username.Your password must be at least 8 characters long and contain upper and lowercase letters, a number without white space.',
						showType:'fade',
						style:{
		                    right:'',
                    		bottom:''
		                }
					});
					die; 
				}else if(flagPasswordLowercase==0){
					$.messager.show({
						title: 'Error',
						msg: 'Your password must contain at least 1 lowercase letter.Your password must be at least 8 characters long and contain upper and lowercase letters, a number without white space.',
						showType:'fade',
						style:{
		                    right:'',
                    		bottom:''
		                }
					});
					die; 
				}else if(flagPasswordUppercase==0){
					$.messager.show({
						title: 'Error',
						msg: 'Your password must contain at least 1 uppercase letter.Your password must be at least 8 characters long and contain upper and lowercase letters, a number without white space.',
						showType:'fade',
						style:{
		                    right:'',
                    		bottom:''
		                }
					});
					die; 
				}else if(flagPasswordNumber==0){
					$.messager.show({
						title: 'Error',
						msg: 'Your password must contain at least 1 number.Your password must be at least 8 characters long and contain upper and lowercase letters, a number without white space.',
						showType:'fade',
						style:{
		                    right:'',
                    		bottom:''
		                }
					});
					die; 
				}else if(flagPasswordWhitespace==0){
					$.messager.show({
						title: 'Error',
						msg: 'Your password must not contain any white space.Your password must be at least 8 characters long and contain upper and lowercase letters, a number without white space.',
						showType:'fade',
						style:{
		                    right:'',
                    		bottom:''
		                }
					});
					die; 
				}else if(flagStaffName==0){
					$.messager.show({
						title: 'Error',
						msg: 'Invalid Staff Name. Staff Name cannot contain any special characters except dots and dashes.',
						showType:'fade',
						style:{
		                    right:'',
                    		bottom:''
		                }
					});
					die; 
				}else if(flagContactNo==0){
					$.messager.show({
						title: 'Error',
						msg: 'Invalid Singapore Contact Number Format.',
						showType:'fade',
						style:{
		                    right:'',
                    		bottom:''
		                }
					});
					die; 
				}else if(flagUserType==0){
					$.messager.show({
						title: 'Error',
						msg: 'Invalid User Type. User Type cannot contain any special characters and numbers.',
						showType:'fade',
						style:{
		                    right:'',
                    		bottom:''
		                }
					});
					die; 
				}else if(flagCentreId==0){
					$.messager.show({
						title: 'Error',
						msg: 'Invalid Centre Id. Centre Id cannot contain any special characters and letters.',
						showType:'fade',
						style:{
		                    right:'',
                    		bottom:''
		                }
					});
					die; 
				}else if(flagEmailFormat==0){
					$.messager.show({
						title: 'Error',
						msg: 'Invalid Email Format.',
						showType:'fade',
						style:{
		                    right:'',
                    		bottom:''
		                }
					});
					die;
				}else if(flagEmailExist==0){
					$.messager.show({
						title: 'Error',
						msg: 'This Email has already been used! Please enter another Email.',
						showType:'fade',
						style:{
		                    right:'',
                    		bottom:''
		                }
					});
					die;
				}else{
					return $(this).form('validate');	
				}		
			},
			url: './CRUDUser/save_user.php',
			success: function(result){	
				var result = eval('('+result+')');
				if (result.success){
					$('#insertform').find('input[name="InsertUsername"]').val('');
					$('#insertform').find('input[name="InsertPassword"]').val('');
					$('#insertform').find('input[name="InsertStaffName"]').val('');
					$('#insertform').find('input[name="InsertContactNumber"]').val('');
					$('#insertform').find('input[name="InsertEmail"]').val('');
					$('#insertdlg').dialog('close');		// close the dialog
					$('#dg').datagrid('reload');	// reload the user data
				} else {
					$.messager.show({
						title: 'Error',
						msg: result.msg,
						showType:'fade',
						style:{
							right:'',
							bottom:''
						}
					});
				}
			}
		});
	}

	function editUser(){
	var row = $('#dg').datagrid('getSelected');
		if(row){
			$('#updatedlg').dialog('open').dialog('setTitle','Edit User');
			$('#updateform').form('load',row);
		}
	}
	
	function updateUser(){
		$('#updateform').form('submit',{
			onSubmit: function(){
				$(this).form('validate');	
				//validate input		
				var flagUserName=0;
				var flagStaffName=0;
				var flagContactNo=0;
				var flagUserType=0;
				var flagCentreName=0;
				var flagEmailFormat=0;
				var flagEmailExist=0;
				$.ajax({
					async : false,
					type : "POST",
					url : "./CRUDUser/validateUpdate.php", //the page/method you wanna validate
					data : {
						UpdateUsername: $("#UpdateUsername").val(),
						UpdateUserType: $('[name="UserType"]').val(),
						UpdateStaffName:$("#UpdateStaffName").val(),
						UpdateContactNo:$("#UpdateContactNumber").val(),
						UpdateStaffName:$("#UpdateStaffName").val(),
						UpdateCentreName: $('[name="CentreId"]').val(),
						UpdateEmail: $("#UpdateEmail").val()
					},
					success : function(data){
						var data = JSON.parse(data);
						flagUserName=data.flagUserName;
						flagStaffName=data.flagStaffName;
						flagContactNo=data.flagContactNo;
						flagUserType=data.flagUserType;
						flagCentreName=data.flagCentreName;
						flagEmailFormat=data.flagEmailFormat;
						flagEmailExist=data.flagEmailExist;
					}
				});
				if(flagUserName==0){
					$.messager.show({
						title: 'Error',
						msg: 'Invalid Username. Username cannot contain any special characters.',
						showType:'fade',
						style:{
		                    right:'',
                    		bottom:''
		                }
					});
					die; 
				}else if(flagStaffName==0){
					$.messager.show({
						title: 'Error',
						msg: 'Invalid Staff Name. Staff Name cannot contain any special characters except dots and dashes.',
						showType:'fade',
						style:{
		                    right:'',
                    		bottom:''
		                }
					});
					die; 
				}else if(flagContactNo==0){
					$.messager.show({
						title: 'Error',
						msg: 'Invalid Singapore Contact Number Format.',
						showType:'fade',
						style:{
		                    right:'',
                    		bottom:''
		                }
					});
					die; 
				}else if(flagUserType==0){
					$.messager.show({
						title: 'Error',
						msg: 'Invalid User Type. User Type cannot contain any special characters and numbers.',
						showType:'fade',
						style:{
		                    right:'',
                    		bottom:''
		                }
					});
					die; 
				}else if(flagCentreName==0){
					$.messager.show({
						title: 'Error',
						msg: 'Invalid Centre Name. Centre Name cannot contain any special characters except brackets.',
						showType:'fade',
						style:{
		                    right:'',
                    		bottom:''
		                }
					});
					die; 
				}else if(flagEmailFormat==0){
					$.messager.show({
						title: 'Error',
						msg: 'Invalid Email Format',
						showType:'fade',
						style:{
		                    right:'',
                    		bottom:''
		                }
					});
					die;
				}else if(flagEmailExist==0){
					$.messager.show({
						title: 'Error',
						msg: 'This Email has already been used! Please enter another Email.',
						showType:'fade',
						style:{
		                    right:'',
                    		bottom:''
		                }
					});
					die;
				}else{
					return $(this).form('validate');	
				}		
			},
			url: './CRUDUser/update_user.php',
			success: function(result){
				var result = eval('('+result+')');
				if(result.success){
					$('#updatedlg').dialog('close');		// close the dialog
					$('#dg').datagrid('reload');	// reload the user data
				}else{
					$.messager.show({
						title: 'Error',
						msg: result.msg,
						showType:'fade',
						style:{
							right:'',
							bottom:''
						}
					});
				}
			}
		});
	}
	
	function removeUser(){
		var row = $('#dg').datagrid('getSelected');
		if (row){
			$.messager.confirm('Confirm Delete this user','Are you sure you want to remove this user?',function(r){
				if (r){
					//validate Username 
					var check = 0;
					$.ajax({
						async : false,
						type : "POST",
						url : "./CRUDUser/validateRemove.php", //the page/method you wanna validate
						data: {
							Username:row.Username
						},
						success : function(data) {
							check=data;
						}
					});
					if(check==0){
						$.messager.show({
							title: 'Error',
							msg: 'Invalid Username Format for Remove.',
							showType:'fade',
							style:{
								right:'',
								bottom:''
							}
						});
					}else{
						$.post('./CRUDUser/remove_user.php',{Username:row.Username},function(result){
							if(result.success){
								$('#dg').datagrid('reload');	// reload the user data
							}else{
								$.messager.show({	// show error message
									title: 'Error',
									msg: "Unable to delete client. This client's data is being used by other records!",
									showType:'fade',
									style:{
										right:'',
										bottom:''
									}
								});
							}
						},'json');
					}
				}
			});
		}
	}

	function getUser(){
		//validate search input	
		var check = 0;
		$.ajax({
			async : false,
			type : "POST",
			url : "./CRUDUser/validateSearch.php", //the page/method you wanna validate
			data: {
				searchid: $('#searchid').val()
			},
			success : function(data) {
				check=data;
			}
		});
		if(check==0){
			$.messager.show({
				title: 'Error',
                msg: 'Invalid Search Input. Search Input cannot contain any special characters except brackets, underscore, address sign and single quatation marks.',
				showType:'fade',
				style:{
					right:'',
					bottom:''
				}
			});
		}else{
			$('#dg').datagrid('load', {
                searchid: $('#searchid').val()
            }); 
		} 	
	}
	function findAll(){
		$('#dg').datagrid('load',{		
		});
	}

	function insertCancel(){
		$('#insertform').find('input[name="InsertUsername"]').val('');
		$('#insertform').find('input[name="InsertPassword"]').val('');
		$('#insertform').find('input[name="InsertStaffName"]').val('');
		$('#insertform').find('input[name="InsertContactNumber"]').val('');
		$('#insertform').find('input[name="InsertEmail"]').val('');
		$('#insertdlg').dialog('close');
	}

	$(function(){
		$("#InsertUserType").next().find("input.validatebox-text").attr("readonly","readonly");	
		$("#InsertCentreId").next().find("input.validatebox-text").attr("readonly","readonly");	
		$("#UpdateUserType").next().find("input.validatebox-text").attr("readonly","readonly");
		$("#UpdateCentreName").next().find("input.validatebox-text").attr("readonly","readonly");		
	});
</script>	
</html>